package com.lzy.business.facade.approval;

import com.github.pagehelper.PageInfo;
import com.lzy.approval.apis.EventProcessServiceApi;
import com.lzy.approval.apis.EventServiceApi;
import com.lzy.approval.apis.ProcessServiceApi;
import com.lzy.approval.dtos.EventDto;
import com.lzy.approval.dtos.EventProcessDto;
import com.lzy.base.apis.SysResourceServiceApi;
import com.lzy.base.dtos.SysResourceDto;
import com.lzy.common.constants.BusinessType;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by WIN7 on 2017/12/15.
 */
@Component
public class EventFacade {
    @Autowired
    EventServiceApi eventServiceApi;

    @Autowired
    EventProcessServiceApi eventProcessServiceApi;

    @Autowired
    SysResourceServiceApi sysResourceServiceApi;

    @Autowired
    ProcessServiceApi processServiceApi;

    /**
     * 查询列表数据   返回json在页面上调用
     */
    public PageInfo<EventDto> queryEventList(Pager pager, EventDto eventDto) {
        return eventServiceApi.queryEventList(pager, eventDto);
    }

    public Boolean eventCreate(EventDto eventDto){
        Ensure.that(eventDto).isNotNull("00000004");
        Long id = eventServiceApi.add(eventDto);
        Ensure.that(id).isNotNull("01001411");
        //流程定义绑定资源
        SysResourceDto sysResourceDto = new SysResourceDto();
        sysResourceDto.setEventId(id);
        sysResourceDto.setId(eventDto.getResourceId());
        Boolean ok2 = sysResourceServiceApi.updateByPrimaryKeySelective(sysResourceDto);
        Ensure.that(ok2).isTrue("01001412");
        //xml文件生成
        File pathPrefix = new File(System.getProperty("user.dir") + "/bpm/" + DateUtil.getDay(new Date())) ;

        if (!pathPrefix.exists())
            pathPrefix.mkdirs();
        String bpmnPath = pathPrefix.getPath() +System.getProperty("file.separator")  + System.currentTimeMillis() + ".bpmn";
        Boolean ok = processServiceApi.createDefinitionFile(bpmnPath, id.toString(), eventDto.getName(), eventDto.getSortIdArr());
        Ensure.that(ok).isTrue("01001413");
        //流程部署
        String processId = processServiceApi.deploymentProcessDefinition(bpmnPath, eventDto.getName());
        Ensure.that(processId).isNotNull("01001414");
        return Boolean.TRUE;
    }

    public Boolean eventUpdate(EventDto eventDto) {
        Ensure.that(eventDto).isNotNull("00000004");
        Boolean flag = eventServiceApi.update(eventDto);
        EventProcessDto eventProcessDto = new EventProcessDto();
        eventProcessDto.setEventId(eventDto.getId());
        Boolean flag1 = eventProcessServiceApi.deleteByEventId(eventProcessDto);
        if (flag == true && flag1 == true) {
            //xml文件生成
            File pathPrefix = new File(System.getProperty("user.dir") + "/bpm/" + DateUtil.getDay(new Date())) ;
            if (!pathPrefix.exists())
                pathPrefix.mkdirs();
            String bpmnPath = pathPrefix.getPath()  +System.getProperty("file.separator") + System.currentTimeMillis() + ".bpmn";
//            String bpmnPath = "d:/process-" + System.currentTimeMillis() + ".bpmn";
            Boolean ok = processServiceApi.createDefinitionFile(bpmnPath, eventDto.getId().toString(), eventDto.getName(), eventDto.getSortIdArr());
            Ensure.that(ok).isTrue("01001413");
            //流程部署
            processServiceApi.deploymentProcessDefinition(bpmnPath, eventDto.getName());
            //审批事件新增
            String[] idArr = eventDto.getIdArr().split(",");
            String[] sortArr = eventDto.getSortArr().split(",");
            String[] nameArr = eventDto.getNameArr().split(",");
            Ensure.that(idArr.length).isEqual(sortArr.length, "01001402");
            Ensure.that(idArr.length).isEqual(nameArr.length, "01001402");
            //流程审批人批量新增
            for (int i=0; i<idArr.length; i++) {
                EventProcessDto eventProcessDto1 = new EventProcessDto();
                eventProcessDto1.setEventId(eventDto.getId());
                eventProcessDto1.setSort(Integer.parseInt(sortArr[i]));
                eventProcessDto1.setUserId(Long.parseLong(idArr[i]));
                eventProcessDto1.setUserName(nameArr[i]);
                Boolean flag2 = eventProcessServiceApi.insert(eventProcessDto1);
                Ensure.that(flag2).isTrue("01001401");
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 查询选择列表
     * @param id
     * @return
     */
    public EventDto queryEventProcessById(Long id) {
        EventDto dto = eventServiceApi.findById(id);
        Ensure.that(dto).isNotNull("01001404");
        //拿到资源，二级id、一级id
        SysResourceDto sysResourceDto = sysResourceServiceApi.selectByPrimaryKey(dto.getResourceId());//获取二级id
        Ensure.that(sysResourceDto).isNotNull("01001405");
        dto.setResourceSecId(sysResourceDto.getPid());
        SysResourceDto resourceDto = sysResourceServiceApi.selectByPrimaryKey(dto.getResourceSecId());//获取一级id
        dto.setResourceSecName(resourceDto.getName());
        Ensure.that(resourceDto).isNotNull("01001406");
        for(int i=1;i>0;i++){
            if(resourceDto.getPid()!=0){
                resourceDto = sysResourceServiceApi.selectByPrimaryKey(resourceDto.getPid());//获取一级id
            }else{
                break;
            }
        }
        dto.setResourceFristId(resourceDto.getId());
        dto.setResourceFristName(resourceDto.getName());
        EventProcessDto eventProcessDto = new EventProcessDto();
        eventProcessDto.setEventId(dto.getId());
        EventDto eventDto = eventProcessServiceApi.queryEvent(dto,eventProcessDto);
        eventDto.setResourceFristName(resourceDto.getName());
        eventDto.setResourceName(sysResourceDto.getName());
        eventDto.setResourceSecName(dto.getResourceSecName());
        return eventDto;
    }

    /**
     * 更新状态，改变sys_resource表中的eventId
     * @param eventDto
     * @return
     */
    public Boolean updateStatus(EventDto eventDto){
        //根据id查询出resourceId
        EventDto eventDto1 = eventServiceApi.findById(eventDto.getId());
        //禁用->启用状态
        //查询出所有该资源id的审批事件列表，并将该事件列表的的所有事件都置为禁用状态
        List<EventDto> eventDtoList = eventServiceApi.queryEventListByResourceId(eventDto1.getResourceId());
        for (EventDto e : eventDtoList) {
            if(e.getStatus() == BusinessType.StatusEnum.ENABLED.getCode()){
                e.setStatus(BusinessType.StatusEnum.DISABLED.getCode());
                Boolean ok = eventServiceApi.updateStatus(e);
                Ensure.that(ok).isTrue("01001409");
            }
        }
        SysResourceDto sysResourceDto = sysResourceServiceApi.selectByPrimaryKey(eventDto1.getResourceId());
        sysResourceDto.setEventId(eventDto.getId());
        Boolean flag = sysResourceServiceApi.updateByPrimaryKeySelective(sysResourceDto);
        Ensure.that(flag).isTrue("01001408");
        return eventServiceApi.updateStatus(eventDto);
    }
}
